package com.sky.financelake.ui.dialog;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.sky.financelake.R;
import com.sky.financelake.bean.dto.RPlateZjlxDto;
import com.sky.financelake.common.Constants;
import com.sky.financelake.databinding.DialogFragmentPlateBinding;
import com.sky.financelake.helper.RedisHelper;
import com.sky.financelake.utils.LocalJsonResolutionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class PlateDialogF extends DialogFragment {

    private static final String TAG = PlateDialogF.class.getCanonicalName();
    private DialogFragmentPlateBinding binding;

    private BarChart barChart;
    private YAxis leftAxis;             //左侧Y轴
    private YAxis rightAxis;            //右侧Y轴
    private XAxis xAxis;                //X轴
    private Legend legend;              //图例
    private LimitLine limitLine;        //限制线
    private List<String> keys = new ArrayList<>();
    private String plateName = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        plateName = bundle.getString("plate_name");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DialogFragmentPlateBinding.inflate(inflater);

        initTitle();

        initBarChart();

        parsePlateData();


        return binding.getRoot();
    }

    private void initTitle() {
        if (plateName.equals(Constants.PLATE_DY)) {
            getDialog().setTitle(getString(R.string.plate_dy));
        } else if (plateName.equals(Constants.PLATE_HY)) {
            getDialog().setTitle(getString(R.string.plate_hy));
        } else if (plateName.equals(Constants.PLATE_GN)) {
            getDialog().setTitle(getString(R.string.plate_gn));
        }
    }

    /**
     * 初始化柱状图外观
     */
    private void initBarChart() {
        barChart = binding.barChart;
        /***图表设置***/
        //背景颜色
        barChart.setBackgroundColor(Color.WHITE);
        //不显示图表网格
        barChart.setDrawGridBackground(false);
        //背景阴影
        barChart.setDrawBarShadow(false);
        barChart.setHighlightFullBarEnabled(false);
        //显示边框
        barChart.setDrawBorders(false);
        //设置动画效果
        barChart.animateY(1000, Easing.Linear);
        barChart.animateX(1000, Easing.Linear);

        Description description = new Description();
        description.setEnabled(false);
        barChart.setDescription(description);


        /***XY轴的设置***/
        //X轴设置显示位置在底部
        xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);

        leftAxis = barChart.getAxisLeft();
        rightAxis = barChart.getAxisRight();
        //保证Y轴从0开始，不然会上移一点

        xAxis.setDrawAxisLine(false);
        leftAxis.setDrawAxisLine(false);
        rightAxis.setDrawAxisLine(false);
        rightAxis.setEnabled(false);


        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(50f);

        ValueFormatter formatterY = new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
//                float v = value / 100000000f;
//                float v_ = (float) (Math.round(v * 100)) / 100;
//                Log.i(TAG, "getFormattedValue: " + value);
                return value + "亿";
            }
        };
        leftAxis.setValueFormatter(formatterY);

        //不显示X轴网格线
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(10, false);
        //右侧Y轴网格线设置为虚线
        xAxis.enableGridDashedLine(10f, 10f, 0f);


        /***折线图例 标签 设置***/
        legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
    }


    /**
     * 柱状图始化设置 一个BarDataSet 代表一列柱状图
     *
     * @param barDataSet 柱状图
     * @param color      柱状图颜色
     */
    private void initBarDataSet(BarDataSet barDataSet, int color) {
        barDataSet.setColor(color);
        barDataSet.setFormLineWidth(1f);
        barDataSet.setFormSize(15.f);
        //不显示柱状图顶部值
        barDataSet.setDrawValues(true);
//        barDataSet.setValueTextSize(10f);
//        barDataSet.setValueTextColor(color);
    }


    public void showBarChart(List<RPlateZjlxDto> dateValueList, String name, int color) {
        ArrayList<BarEntry> entries = new ArrayList<>();
        ValueFormatter formatterX = new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                Log.i(TAG, "getFormattedValue: " + value);
                return dateValueList.get((int) value).getName().substring(0, 2);
            }
        };
        //X轴自定义值
        xAxis.setValueFormatter(formatterX);
        for (int i = 0; i < dateValueList.size(); i++) {
            float v = dateValueList.get(i).getZjlx() / 100000000f;
            float v_ = (float) (Math.round(v * 100)) / 100;
            /**
             * 此处还可传入Drawable对象 BarEntry(float x, float y, Drawable icon)
             * 即可设置柱状图顶部的 icon展示
             */

            BarEntry barEntry = new BarEntry(i, v_);
            entries.add(barEntry);
        }
        // 每一个BarDataSet代表一类柱状图
        BarDataSet barDataSet = new BarDataSet(entries, name);
        initBarDataSet(barDataSet, color);

//        // 添加多个BarDataSet时
//        ArrayList<IBarDataSet> dataSets = new ArrayList<>();
//        dataSets.add(barDataSet);
//        BarData data = new BarData(dataSets);

        BarData data = new BarData(barDataSet);
        data.setBarWidth(.5f);
        barChart.setData(data);
        barChart.setVisibleXRangeMaximum(10f);
        //更新
        barChart.notifyDataSetChanged();
        barChart.invalidate();
    }

    private void parsePlateData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Timer timer = new Timer();
                Map<String, String> r = new TreeMap<>();
                HashMap<String, String> map = (HashMap<String, String>) RedisHelper.getInstance().hgetAll(plateName);
                map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> {
                    keys.add(x.getKey());
                    r.put(x.getKey(), x.getValue());
                });
                Set set = r.keySet();
                Iterator iter = set.iterator();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            if (iter.hasNext()) {
                                String key = (String) iter.next();
                                List<RPlateZjlxDto> beans = LocalJsonResolutionUtils.JsonArrayToList(r.get(key), RPlateZjlxDto.class);
                                if (beans.size() > 6) {
                                    List tmp = beans.subList(6, beans.size());
                                    beans.removeAll(tmp);
                                }
                                requireActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showBarChart(beans, getString(R.string.zjlx), getResources().getColor(R.color.design_default_color_error));
                                    }
                                });
                            } else {
                                this.cancel();
                            }
                        } catch (Exception e) {
                            Log.i(TAG, "run: " + e.getLocalizedMessage());
                        }
                    }
                }, 1000, 1000);
            }
        }).start();

    }

}
